package org.example.auth.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.example.auth.service.SysLoginService;
import org.example.auth.vo.LoginForm;
import org.example.common.base.util.jwt.JwtUtils;
import org.example.common.base.util.web.R;
import org.example.common.security.auth.AuthUtil;
import org.example.common.security.service.TokenService;
import org.example.common.security.util.SecurityUtils;
import org.example.system.api.entity.LoginUser;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @version 1.0.0
 * @className: TokenController
 * @description:
 * @author: LiJunYi
 * @create: 2022/8/2 15:28
 */
@RestController
public class TokenController
{
    private final TokenService tokenService;

    private final SysLoginService sysLoginService;

    /**
     * 注入bean
     *
     * @param tokenService    令牌服务
     * @param sysLoginService 系统登录服务
     */
    public TokenController(TokenService tokenService, SysLoginService sysLoginService) {
        this.tokenService = tokenService;
        this.sysLoginService = sysLoginService;
    }

    /**
     * 登录
     *
     * @param form 接收的登录用户数据
     * @return {@link R}<{@link ?}>
     */
    @PostMapping("login")
    public R<?> login(@RequestBody LoginForm form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 注销
     *
     * @param request 请求
     * @return {@link R}<{@link ?}>
     */
    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StrUtil.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    /**
     * 刷新token
     *
     * @param request 请求
     * @return {@link R}<{@link ?}>
     */
    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (ObjectUtil.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }
}
